
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.*;
import java.util.Scanner;

public class DBUtil {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("abc123");

        Connection connection = dataSource.getConnection();

        //添加
        for(int i = 1; i<=3; i++) {
            String sql = "insert into info values(?,?)";
            System.out.println("请输入第 "  + i + "个人的名字和密码:" );
            PreparedStatement statement = connection.prepareStatement(sql);

            statement.setString(1,scanner.next());
            statement.setString(2,scanner.next());

            int n = statement.executeUpdate();
            System.out.println("成功添加人数: " + n);
            statement.close();;
        }

        //删除自己的那一条
        System.out.println("正在删除:");
        String sql = "delete from info where name = '王丛发'";
        PreparedStatement statement = connection.prepareStatement(sql);
        int n = statement.executeUpdate();
        System.out.println("成功删除人数: " + n);

        //将前一个人的学号修改为1234
        System.out.println("修改密码:");
        sql = "update info set password = 1234 where name = '张三'";
        statement = connection.prepareStatement(sql);
        n = statement.executeUpdate();
        System.out.println("成功更新人数: " + n);

        //查询
        System.out.println("查询结果如下: ");
        sql = "select * from info";
        statement = connection.prepareStatement(sql);
        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getString("name") + " " + rs.getString("password"));
        }
        connection.close();
    }
}